import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import NProgress from 'nprogress'

// Create axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 60000, // 60 seconds for device diagnostic operations
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// Loading instance
let loadingInstance = null
let loadingCount = 0

// Show loading
const showLoading = (options = {}) => {
  if (loadingCount === 0) {
    loadingInstance = ElLoading.service({
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)',
      ...options
    })
  }
  loadingCount++
}

// Hide loading
const hideLoading = () => {
  loadingCount--
  if (loadingCount <= 0) {
    loadingCount = 0
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }
  }
}

// Request interceptor
service.interceptors.request.use(
  config => {
    // Start progress bar
    NProgress.start()

    // Show loading for non-GET requests or specific requests
    if (config.loading !== false && (config.method !== 'get' || config.showLoading)) {
      showLoading({
        text: config.loadingText || '请稍候...',
        target: config.loadingTarget
      })
    }

    // Add timestamp to prevent caching
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    // Add authorization header if token exists
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // Log request in development
    if (import.meta.env.DEV) {
      console.log(
        '🚀 Request:',
        config.method?.toUpperCase(),
        config.url,
        config.data || config.params
      )
    }

    return config
  },
  error => {
    console.error('Request error:', error)
    NProgress.done()
    hideLoading()
    ElMessage.error('请求配置错误')
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  response => {
    // Stop progress bar
    NProgress.done()
    hideLoading()
    const { data, status, config } = response
    if (import.meta.env.DEV) {
      console.log('📥 Response:', config.method?.toUpperCase(), config.url, status, data)
    }
    
    // 对于所有HTTP状态码为2xx的响应，都认为是成功的
    if (status >= 200 && status < 300) {
      if (
        response.headers['content-type']?.includes('application/octet-stream') ||
        response.headers['content-type']?.includes('image/') ||
        config.responseType === 'blob'
      ) {
        return response
      }
      
      // 直接返回完整的响应数据，让业务层处理success和code字段
      return data
    }

    ElMessage.error('请求失败')
    return Promise.reject(new Error('请求失败'))
  },
  error => {
    // Stop progress bar
    NProgress.done()
    hideLoading()

    console.error('Response error:', error)

    const { response, message, code } = error

    // Handle different error types
    if (response) {
      const { status, data } = response

      switch (status) {
        case 400:
          ElMessage.error(data?.message || '请求参数错误')
          break
        case 401:
          ElMessage.error('未授权，请重新登录')
          // Clear token and redirect to login
          localStorage.removeItem('token')
          // window.location.href = '/login'
          break
        case 403:
          ElMessage.error('拒绝访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 408:
          ElMessage.error('请求超时')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        case 502:
          ElMessage.error('网关错误')
          break
        case 503:
          ElMessage.error('服务不可用')
          break
        case 504:
          ElMessage.error('网关超时')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (code === 'ECONNABORTED' || message.includes('timeout')) {
      ElMessage.error('请求超时，请检查网络连接')
    } else if (code === 'ERR_NETWORK' || message.includes('Network Error')) {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error(message || '请求失败')
    }

    return Promise.reject(error)
  }
)

// Request methods
const request = {
  get(url, params = {}, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      ...config
    })
  },

  post(url, data = {}, config = {}) {
    return service({
      method: 'post',
      url,
      data,
      ...config
    })
  },

  put(url, data = {}, config = {}) {
    return service({
      method: 'put',
      url,
      data,
      ...config
    })
  },

  patch(url, data = {}, config = {}) {
    return service({
      method: 'patch',
      url,
      data,
      ...config
    })
  },

  delete(url, config = {}) {
    return service({
      method: 'delete',
      url,
      ...config
    })
  },

  upload(url, formData, config = {}) {
    return service({
      method: 'post',
      url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    })
  },

  download(url, params = {}, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      responseType: 'blob',
      ...config
    })
  }
}

// Setup function for main.js
export const setupAxios = () => {
  // Set default base URL
  if (import.meta.env.VITE_API_BASE_URL) {
    service.defaults.baseURL = import.meta.env.VITE_API_BASE_URL
  }

  console.log('🔧 Axios configured with base URL:', service.defaults.baseURL)
}

// Export service and request methods
export default service
export { request }

// Utility functions
export const createFormData = data => {
  const formData = new FormData()
  Object.keys(data).forEach(key => {
    if (data[key] !== null && data[key] !== undefined) {
      formData.append(key, data[key])
    }
  })
  return formData
}

export const downloadFile = (response, filename) => {
  const blob = new Blob([response.data])
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename || 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

export const getResponseFilename = response => {
  const contentDisposition = response.headers['content-disposition']
  if (contentDisposition) {
    const matches = contentDisposition.match(/filename="?([^"]+)"?/)
    if (matches && matches[1]) {
      return decodeURIComponent(matches[1])
    }
  }
  return 'download'
}
